import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
import { aiService, ProductInfo } from '@/lib/aiService';

// 商品分类
const categories = [
  { id: 'electronics', name: '电子产品' },
  { id: 'books', name: '书籍资料' },
  { id: 'sports', name: '运动器材' },
  { id: 'home', name: '家居用品' },
  { id: 'fashion', name: '服饰鞋包' },
  { id: 'beauty', name: '美妆个护' },
  { id: 'toys', name: '玩具乐器' },
  { id: 'other', name: '其他物品' }
];

// 新旧程度选项
const conditions = [
  { id: 'brand-new', name: '全新' },
  { id: 'like-new', name: '九成新' },
  { id: 'good', name: '良好' },
  { id: 'fair', name: '一般' }
];

// 交易地点选项
const locations = [
  { id: 'main', name: '主校区' },
  { id: 'east', name: '东校区' },
  { id: 'west', name: '西校区' },
  { id: 'south', name: '南校区' },
  { id: 'north', name: '北校区' }
];

export default function PostProduct() {
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    price: '',
    originalPrice: '',
    category: '',
    condition: '',
    location: '',
    tags: ''
  });
  const [images, setImages] = useState<File[]>([]);
  const [imagePreviews, setImagePreviews] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isRiskChecking, setIsRiskChecking] = useState(false);
  const [riskCheckResult, setRiskCheckResult] = useState<any>(null);
  const navigate = useNavigate();
  const { theme } = useTheme();

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 处理图片上传
  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      const newImages = Array.from(e.target.files);
      setImages([...images, ...newImages]);
      
      // 生成图片预览
      const previews = newImages.map(file => URL.createObjectURL(file));
      setImagePreviews([...imagePreviews, ...previews]);
    }
  };

  // 移除图片
  const removeImage = (index: number) => {
    const newImages = [...images];
    newImages.splice(index, 1);
    setImages(newImages);
    
    const newPreviews = [...imagePreviews];
    URL.revokeObjectURL(newPreviews[index]);
    newPreviews.splice(index, 1);
    setImagePreviews(newPreviews);
  };

  // 表单验证
  const validateForm = (): boolean => {
    const { title, description, price, category, condition, location } = formData;
    
    // 验证表单基本信息
    if (!title.trim()) {
      toast.error('请输入商品标题');
      return false;
    }
    
    if (!description.trim()) {
      toast.error('请输入商品描述');
      return false;
    }
    
    if (!price || isNaN(Number(price)) || Number(price) <= 0) {
      toast.error('请输入有效的价格');
      return false;
    }
    
    if (!category) {
      toast.error('请选择商品分类');
      return false;
    }
    
    if (!condition) {
      toast.error('请选择新旧程度');
      return false;
    }
    
    if (!location) {
      toast.error('请选择交易地点');
      return false;
    }
    
    if (images.length === 0) {
      toast.error('请至少上传一张商品图片');
      return false;
    }
    
    return true;
  };

  // AI风险检查
  const checkProductRisk = async () => {
    if (!validateForm()) {
      return false;
    }
    
    setIsRiskChecking(true);
    
    try {
      const productInfo: ProductInfo = {
        title: formData.title,
        description: formData.description,
        category: categories.find(c => c.id === formData.category)?.name || '',
        images: imagePreviews
      };
      
      const result = await aiService.checkProductRisk(productInfo);
      setRiskCheckResult(result);
      
      if (result.isRisky && result.riskLevel === 'high') {
        toast.error('商品存在高风险问题，请修改后重新提交');
        return false;
      } else if (result.isRisky) {
        toast.warning(`商品存在潜在风险: ${result.riskReasons.join('，')}`);
        // 中等风险允许继续，但显示警告
      } else {
        toast.success('商品风控检查通过');
      }
      
      return true;
    } catch (error) {
      console.error('风险检查失败:', error);
      toast.error('风险检查失败，请稍后再试');
      return false;
    } finally {
      setIsRiskChecking(false);
    }
  };
  

  // 提交表单
  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 先进行AI风险检查
    const riskCheckPassed = await checkProductRisk();
    if (!riskCheckPassed) {
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 模拟API请求
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 在实际应用中，这里应该将表单数据和图片发送到服务器
      console.log('提交的商品数据:', { ...formData, images });
      
      toast.success('商品发布成功！');
      
      // 发布成功后跳转到首页
      setTimeout(() => {
        navigate('/');
      }, 1000);
    } catch (error) {
      toast.error('发布失败，请稍后重试');
      console.error('发布商品时出错:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className={cn("min-h-screen bg-gray-50 dark:bg-gray-900 py-8 px-4 sm:px-6 lg:px-8")}>
      <div className="max-w-3xl mx-auto">
        <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm p-6">
          <div className="flex items-center justify-between mb-6">
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">发布商品</h1>
            <span className="text-sm text-gray-500 dark:text-gray-400">
              请填写商品信息，确保内容真实有效
            </span>
          </div>
          
          <form onSubmit={handleSubmit}>
            {/* 商品标题 */}
            <div className="mb-6">
              <label htmlFor="title" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                商品标题 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="title"
                name="title"
                value={formData.title}
                onChange={handleInputChange}
                placeholder="请输入商品标题，如：九成新 MacBook Pro 2023"
                className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                请简要描述您的商品，吸引买家注意
              </p>
            </div>
            
            {/* 商品描述 */}
            <div className="mb-6">
              <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                商品描述 <span className="text-red-500">*</span>
              </label>
              <textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                placeholder="请详细描述商品的情况，包括品牌、型号、购买时间、使用情况、物品瑕疵等信息"
                rows={5}
                className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                详细的描述有助于买家更好地了解商品，提高交易成功率
              </p>
            </div>
            
            {/* 价格信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
              <div>
                <label htmlFor="price" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  出售价格 (元) <span className="text-red-500">*</span>
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <span className="text-gray-500 dark:text-gray-400">¥</span>
                  </div>
                  <input
                    type="number"
                    id="price"
                    name="price"
                    value={formData.price}
                    onChange={handleInputChange}
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                    className="w-full pl-8 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  />
                </div>
              </div>
              
              <div>
                <label htmlFor="originalPrice" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  原价 (元)
                </label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <span className="text-gray-500 dark:text-gray-400">¥</span>
                  </div>
                  <input
                    type="number"
                    id="originalPrice"
                    name="originalPrice"
                    value={formData.originalPrice}
                    onChange={handleInputChange}
                    placeholder="0.00"
                    min="0"
                    step="0.01"
                    className="w-full pl-8 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                  />
                </div>
              </div>
            </div>
            
            {/* 商品分类 */}
            <div className="mb-6">
              <label htmlFor="category" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                商品分类 <span className="text-red-500">*</span>
              </label>
              <select
                id="category"
                name="category"
                value={formData.category}
                onChange={handleInputChange}
                className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="">请选择分类</option>
                {categories.map(category => (
                  <option key={category.id} value={category.id}>
                    {category.name}
                  </option>
                ))}
              </select>
            </div>
            
            {/* 其他信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
              <div>
                <label htmlFor="condition" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  新旧程度 <span className="text-red-500">*</span>
                </label>
                <select
                  id="condition"
                  name="condition"
                  value={formData.condition}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                >
                  <option value="">请选择新旧程度</option>
                  {conditions.map(condition => (
                    <option key={condition.id} value={condition.id}>
                      {condition.name}
                    </option>
                  ))}
                </select>
              </div>
              
              <div>
                <label htmlFor="location" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  交易地点 <span className="text-red-500">*</span>
                </label>
                <select
                  id="location"
                  name="location"
                  value={formData.location}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                >
                  <option value="">请选择交易地点</option>
                  {locations.map(location => (
                    <option key={location.id} value={location.id}>
                      {location.name}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            
            {/* 标签 */}
            <div className="mb-6">
              <label htmlFor="tags" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                商品标签
              </label>
              <input
                type="text"
                id="tags"
                name="tags"
                value={formData.tags}
                onChange={handleInputChange}
                placeholder="请输入商品标签，用逗号分隔，如：MacBook,笔记本电脑,M3"
                className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                最多添加5个标签，有助于商品被更多买家发现
              </p>
            </div>
            
            {/* 图片上传 */}
            <div className="mb-8">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                商品图片 <span className="text-red-500">*</span>
              </label>
              
              {/* 图片预览区 */}
              {imagePreviews.length > 0 && (
                <div className="grid grid-cols-4 gap-4 mb-4">
                  {imagePreviews.map((preview, index) => (
                    <div key={index} className="relative">
                      <img 
                        src={preview} 
                        alt={`预览 ${index + 1}`}
                        className="w-full h-24 object-cover rounded-lg"
                      />
                      <button
                        type="button"
                        onClick={() => removeImage(index)}
                        className="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600"
                      >
                        <i className="fa-solid fa-times text-xs"></i>
                      </button>
                    </div>
                  ))}
                </div>
              )}
              
              {/* 上传按钮 */}
              <div className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-6 text-center hover:border-indigo-500 cursor-pointer">
                <input
                  type="file"
                  multiple
                  accept="image/*"
                  onChange={handleImageUpload}
                  className="hidden"
                  id="imageUpload"
                />
                <label htmlFor="imageUpload" className="cursor-pointer">
                  <i className="fa-solid fa-cloud-arrow-up text-2xl text-gray-400 mb-2"></i>
                  <div className="text-sm font-medium text-gray-700 dark:text-gray-300">
                    点击上传图片
                  </div>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                    支持 JPG、PNG、GIF 格式，最多上传9张，单张不超过5MB
                  </p>
                </label>
              </div>
            </div>
            
            {/* 提交按钮 */}
             <div className="flex justify-end space-x-4">
                <button
                  type="button"
                  onClick={() => navigate(-1)}
                  disabled={isSubmitting || isRiskChecking}
                  className="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"
                >
                  取消
                </button>
                
                <button
                  type="submit"
                  disabled={isSubmitting || isRiskChecking}
                  className={`px-6 py-2 rounded-lg text-white bg-indigo-600 dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600 ${
                    isSubmitting || isRiskChecking ? 'opacity-75 cursor-not-allowed' : ''
                  }`}
                >
                  {isRiskChecking ? (
                    <>
                      <i className="fa-solid fa-shield-halved fa-spin mr-2"></i>
                      安全检查中...
                    </>
                  ) : isSubmitting ? (
                    <>
                      <i className="fa-solid fa-circle-notch fa-spin mr-2"></i>
                      发布中...
                    </>
                  ) : (
                    <>
                      <i className="fa-solid fa-paper-plane mr-2"></i>
                      发布商品
                    </>
                  )}
                </button>
              </div>
              
              {/* 风险检查结果显示 */}
              {riskCheckResult && (
                <div className={`mt-4 p-4 rounded-lg ${
                  riskCheckResult.isRisky 
                    ? riskCheckResult.riskLevel === 'high' 
                      ? 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800' 
                      : 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800' 
                    : 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
                }`}>
                  <h4 className={`font-medium mb-2 ${
                    riskCheckResult.isRisky 
                      ? riskCheckResult.riskLevel === 'high' 
                        ? 'text-red-800 dark:text-red-400' 
                        : 'text-yellow-800 dark:text-yellow-400' 
                      : 'text-green-800 dark:text-green-400'
                  }`}>
                    {riskCheckResult.isRisky ? '⚠️ 风险提示' : '✅ 安全检查通过'}
                  </h4>
                  {riskCheckResult.riskReasons && riskCheckResult.riskReasons.length > 0 && (
                    <ul className="list-disc list-inside text-sm mb-2">
                      {riskCheckResult.riskReasons.map((reason: string, index: number) => (
                        <li key={index} className={riskCheckResult.isRisky ? 'text-red-700 dark:text-red-300' : 'text-green-700 dark:text-green-300'}>
                          {reason}
                        </li>
                      ))}
                    </ul>
                  )}
                  <p className="text-sm text-gray-700 dark:text-gray-300">{riskCheckResult.suggestion}</p>
                </div>
              )}
          </form>
        </div>
      </div>
    </div>
  );
}